﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace RoketSolutions.SP2010.Infrostructure.Common.Extensions
{
    public static class Types
    {
         public static Type FindGenericInterface(this Type sourceType, Type interfaceType)
         {
             Func<Type, bool> finder = type => type.IsGenericType && (type.GetGenericTypeDefinition() == interfaceType);
             return finder(sourceType)
                        ? sourceType
                        : sourceType.GetInterfaces().FirstOrDefault(finder);
         }

        public static bool IsArray(this Type sourceType)
        {
            if (sourceType == typeof(string))
                return false;

            return sourceType.IsArray || sourceType.FindGenericInterface(typeof(IEnumerable<>)) != null;
        }
        
        public static bool IsComplexType(this Type sourceType)
        {
            return !TypeDescriptor.GetConverter(sourceType).CanConvertFrom(typeof(string));
        }
    }
}